package com.itheima.controller;

import com.itheima.domain.Option;
import com.itheima.domain.Pow;
import com.itheima.domain.Student;
import com.itheima.domain.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.Socket;
import java.util.List;
import java.util.Scanner;

public class UserController {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);
    public Scanner sc = new Scanner(System.in);
    private User adminuser;

    public UserController() {
        this.adminuser = new User("localhost","localhost",Pow.STUDENT);
    }

    public UserController(User user) {
//        LOGGER.info("创建UserController对象:" + user.toString());
        this.adminuser = user;
    }

    // 客服的功能入口
    public final void start() throws Exception {
        while (true) {
            //1. 展示二级菜单列表
            System.out.println("********欢迎来到权限管理系统********");
            String rootStr = adminuser.getPow().compareTo(Pow.ADMIN) == 0 ? "  (锁定!)" : "";
            System.out.println("1. 添加用户" + rootStr);
            System.out.println("2. 删除用户" + rootStr);
            System.out.println("3. 修改用户" + rootStr);
            System.out.println("4. 查看用户");
            System.out.println("5. 退出");

            //2. 用户录入选项,匹配对应功能
            String option = sc.next();

            if (adminuser.getPow().compareTo(Pow.ADMIN) == 0) {
                if (!option.equals("4") && !option.equals("5")) {
                    System.out.println("权限不足,无法执行此操作");
                    continue;
                }
            }
            //3. 基于switch来进行菜单功能路由
            switch (option) {
                case "1":
                    addUser();
                    break;
                case "2":
                    delectUser();
                    break;
                case "3":
                    updateUser();
                    break;
                case "4":
                    findAllUser();
                    break;
                case "5":
                    System.out.println("感谢使用权限管理系统,再见!");
                    return;  // return 结束的当前方法!
                default:
                    System.out.println("输入有误!");
                    break;
            }
        }
    }

    private void addUser() {
        //1. 采集用户信息-- 拿到要添加的学生信息
        System.out.println("请输入用户名:");
        String name = sc.next();
        System.out.println("请输入密码:");
        String pwd = sc.next();
        System.out.println("请选择要赋予的权限:");
        System.out.println("1.管理员   2.教师用户  3.学生用户");
        Pow pow = null;
        switch (sc.next()) {
            case "1":
                pow = Pow.ADMIN;
                break;
            case "2":
                pow = Pow.TEACHER;
                break;
            case "3":
                pow = Pow.STUDENT;
                break;
            default:
                System.out.println("无效指令,设定为默认值");
                pow = Pow.STUDENT;
                break;
        }

        if (pow.compareTo(adminuser.getPow()) > 0) {
            //封装成user对象
            User user = new User(name, pwd, pow);
            addUser(user);

        } else {
            System.out.println("权限不足");
        }
    }

    public User addUser(String name, String pwd) {
        LOGGER.info("调用注册功能:" + name + "&" + pwd);
        User user = new User(name, pwd, Pow.STUDENT);
        if (addUser(user)) {
            LOGGER.info("注册成功" + user);
            return user;
        } else {
            return null;
        }
    }

    private boolean addUser(User user) {
        LOGGER.info("发送添加操作请求:" + user.toString());
        //发送请求给服务器,执行添加业务操作
        Socket socket = getSocket();
        //设置报文
        String clientMsg = Option.ADD_USER + "&" + user.toString();
        String resultInfo = null;
        try {
            //创建输出流,传入服务器
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            bw.write(clientMsg);
            LOGGER.info("发送请求给服务器:" + clientMsg);
            bw.newLine();
            bw.flush();

            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            resultInfo = br.readLine();
            System.out.println(resultInfo);
            LOGGER.info("接收服务器响应回的数据:" + resultInfo);
            socket.close();
        } catch (IOException e) {
            LOGGER.error("客户端出现异常:" + e.getMessage());
        }
        return "添加成功!".equals(resultInfo);
    }

    private void delectUser() {
        System.out.println("请输入要删除的用户姓名");
        String id = sc.next();
        String clientMsg = Option.DELECT_USER + "&" + id + "," + adminuser.getPow();
        LOGGER.info("执行删除操作,发送请求为:" + clientMsg);
        System.out.println(sendMsgToServer(clientMsg));

    }

    private void updateUser() {
        //1. 采集用户信息-- 拿到要添加的学生信息
        System.out.println("请输入要修改的用户名:");
        String name = sc.next();
        System.out.println("请输入修改后的密码:");
        String pwd = sc.next();
        System.out.println("请选择要赋予的权限:");
        System.out.println("1.管理员   2.教师用户  3.学生用户");
        Pow pow = null;
        switch (sc.next()) {
            case "1":
                pow = Pow.ADMIN;
                break;
            case "2":
                pow = Pow.TEACHER;
                break;
            case "3":
                pow = Pow.STUDENT;
                break;
            default:
                System.out.println("无效指令,设定为默认值");
                pow = Pow.STUDENT;
                break;
        }
        if (pow.compareTo(adminuser.getPow()) > 0) {
            //封装成user对象
            User user = new User(name, pwd, pow);

            //调用方法,将其传入服务器,并接受返回数据
            LOGGER.info("执行添加学生,发送信息为: "+Option.UPDATE_USER + "&" + user.toString());
            System.out.println(sendMsgToServer(Option.UPDATE_USER + "&" + user.toString()));
        } else {
            System.out.println("权限不足");
        }
    }

    private void findAllUser() {
        try {
            //1. 请求服务器,获取列表数据
            LOGGER.info("执行查看用户,发送请求为:" + Option.FINDALL_USER + "&itheima");
            Socket socket = getSocket();
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            bw.write(Option.FINDALL_USER + "&itheima");
            bw.newLine();
            bw.flush();

            //2. 接收服务器响应回来的结果
            InputStream is = socket.getInputStream();
            ObjectInputStream ois = new ObjectInputStream(is);
            List<User> list = (List<User>) ois.readObject();
            ois.close();
            socket.close();
            LOGGER.info("执行查看学生,接收响应为:" + list);

            //3. 判断系统有没有数据
            if (list == null || list.size() == 0) {
                System.out.println("系统暂无数据,请添加后重试!");
            } else {
                System.out.println("用户名\t密码\t权限");
                list.forEach(stu -> System.out.println(stu.getUsername() + "\t" + stu.getPassworld() + "\t" + stu.getPow()));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    //发送请求给服务器,返回服务器传回结果
    private Object sendMsgToServer(String clientMsg) {
        LOGGER.info("发送请求:" + clientMsg + "给服务器");
        String resultInfo = null;
        try {
            //发送请求给服务器,进行业务操作
            Socket socket = getSocket();
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            bw.write(clientMsg);
            bw.newLine();
            bw.flush();
            socket.shutdownOutput();

            //接收服务器返回数据,并展示给用户
            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            resultInfo = br.readLine();
            bw.close();
            socket.close();
            LOGGER.info("服务器响应回数据:" + clientMsg);
        } catch (IOException e) {
            e.printStackTrace();
            LOGGER.error("客户端出现异常:" + e.getMessage());
        }
        return resultInfo;
    }

    //封装一个方法,专门获取socket对象
    private Socket getSocket() {
        try {
            return new Socket("127.0.0.1", 10001);
        } catch (Exception e) {
            return null;
        }
    }
}
